<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

/**
 * 商品规格属性
 * @package app\erp\admin
 */
class GoodsSpecificationsAttribute extends Admin
{
    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index(){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		$data = input();

        $goods_id = isset($data['goods_id']) ? $data['goods_id'] : 0;
        $specifications_id = isset($data['specifications_id']) ? $data['specifications_id'] : 0;

		$map[] = ['goods_id', '=', $goods_id];
		$map[] = ['specifications_id', '=', $specifications_id];
		
		$btn_access = [
			'title' => '编辑',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('edit', ['id' => '__id__']),
		];
		
		$btn_add = [
			'title' => '添加',
			'icon'  => 'fa fa-plus-circle',
			'class' => 'btn btn-primary',
			'href'  => url('add', ['goods_id' => $goods_id, 'specifications_id' => $specifications_id]),
		];
		
		$btn_delete = [
			'title' => '删除',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('delete', ['id' => '__id__']),
		];

		// 数据列表
		$data_list = model('erp/ErpGoodsSpecificationsAttribute', 'model') -> where($map) -> order('sort asc') -> paginate();
		//dump($data_list);
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('属性') // 设置页面标题
            //->setTableName('video_play_class') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['attribute_id', 'id'],
                // ['attribute_title', '属性名称','text.edit'],
                ['attribute_title', '属性名称'],
                ['sort', '排序','text.edit'],
                ['right_button', '操作', 'btn']
            ])
			->addTopButton('custom', $btn_add, true) // 添加授权按钮
			->addRightButton('custom', $btn_access, true) // 添加授权按钮
			->addRightButton('custom', $btn_delete) // 添加授权按钮
			->setRowList($data_list) // 设置表格数据,
            ->fetch(); // 渲染页面
    }
	
	public function add($goods_id = '', $specifications_id = ''){
		// 保存数据
		if ($this->request->isPost()) {
			$data = $this->request->post('', null, 'trim');
			$attribute_id 	= isset($data['attribute_id']) ? $data['attribute_id'] : '';
			$sort  			= isset($data['sort']) ? $data['sort'] : '';
			if(empty($attribute_id)){
				$this->error('请选择属性');
			}

			$map = [];
			$map[] = ['goods_id', 'eq', $goods_id];
			$map[] = ['specifications_id', 'neq', $specifications_id];
			$old_attribute_id = model('ErpGoodsSpecificationsAttribute') -> where($map) -> column('attribute_id,attribute_title');
			
			$goods_name = model('ErpGoods') -> find($goods_id) -> goods_name;
			
			$sku_arr = [];
			foreach($attribute_id as $aid2){
				$attribute_title2 = model('ErpSpecificationsAttribute') -> find($aid2) -> title;

				$data = [];
				$data['goods_id'] 			= $goods_id;
				$data['specifications_id']  = $specifications_id;
				$data['attribute_id']  		= $aid2;
				$data['attribute_title']  	= $attribute_title2;
				$data['sort']  				= 100;
				$rel = model('ErpGoodsSpecificationsAttribute') -> isUpdate(false) ->data($data, true) -> save();
				if(!$rel){
					$this->error($rel['message']);
				}
				
				foreach($old_attribute_id as $aid1 => $attribute_title1){
					$attribute_title = $attribute_title1 . ' ' . $attribute_title2;
					$sku_arr[] = [
						'goods_id' 		=> $goods_id,
						'goods_name' 	=> $goods_name,
						'specifications1_attribute_id' => $aid1,
						'specifications2_attribute_id' => $aid2,
						'goods_specifications'  	   => $attribute_title,
						'sku_status' 		=> 2,
						'price' 			=> 0,
						'purchase_price' 	=> 0,
					];
				}
			}
			$rel = model('ErpGoodsSku') -> saveAll($sku_arr);
			if($rel){
				$this->success('添加成功', '', '_parent_reload');
			}else{
				$this->error($rel['message']);
			}
		}
		$map = [];
		$map['goods_id'] 		  = $goods_id;
		$map['specifications_id'] = $specifications_id;
		$attribute_id = model('ErpGoodsSpecificationsAttribute') -> where($map) -> column('attribute_id');
		
		$specifications_id = model('ErpGoodsClasstempSpecifications') -> find($specifications_id) -> specifications_id;//关联表中查出实际规格id
		
		$map = [];
		$map[] = ['sid', '=', $specifications_id];
		$map[] = ['id', 'not in', $attribute_id];
		$specifications = model('ErpSpecificationsAttribute') -> where($map) -> column('id,title');
		
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('添加属性')
            ->addFormItems([
				['checkbox', 'attribute_id', '规格属性', '', $specifications],
            ])
			// ->addText('sort', '排序')
            ->fetch();
	}
	
	public function edit($id = ''){
		if ($id === '') $this->error('缺少参数');
		// 保存数据
		if ($this->request->isPost()) {
			$data = $this->request->post('', null, 'trim');
			$data['id'] = $id;
			$attribute_title = isset($data['attribute_title']) ? $data['attribute_title'] : '';
			$sort  			 = isset($data['sort']) ? $data['sort'] : '';
			
			if($attribute_title == ''){
				$this->error('请输入属性名称');
			}
			if($sort == ''){
				$this->error('请输入排序');
			}
			
			$map = [];
			$map['id'] = $id;
			
			$data = [];
			$data['attribute_title'] = $attribute_title;
			$data['sort'] 			 = $sort;
			$rel = model('ErpGoodsSpecificationsAttribute') -> update($data ,$map);
			if($rel){
				$info = model('ErpGoodsSpecificationsAttribute') -> find($id);
				$goods_id     = $info['goods_id'];
				$attribute_id = $info['attribute_id'];

				$map1 = [
					['goods_id', '=', $goods_id],
					['specifications1_attribute_id', '=', $attribute_id],
				];
				$map2 = [
					['goods_id', '=', $goods_id],
					['specifications2_attribute_id', '=', $attribute_id],
				];

				$sku_info = model('ErpGoodsSku') -> whereOr([$map1, $map2]) ->  column('id,specifications1_attribute_id as a1,specifications2_attribute_id as a2');
				$sku_arr = [];
				foreach($sku_info as $val){
					$map = [];
					$map[] = ['goods_id', '=', $goods_id];
					$map[] = ['attribute_id', 'in', [$val['a1'], $val['a2']]];
					
					$attribute_title = model('ErpGoodsSpecificationsAttribute') -> where($map) -> column('attribute_title');
                    $goods_specifications = $attribute_title[0];
					if(!empty($attribute_title[1])) $goods_specifications = $attribute_title[0] . ' ' . $attribute_title[1];
					
					$sku_arr[] = [
						'id' 					=> $val['id'],
						'goods_specifications'  => $goods_specifications,
					];
				}
				model('ErpGoodsSku') -> saveAll($sku_arr);
				
				$this->success('编辑成功', '', '_parent_reload');
			}else{
				$this->error($rel['message']);
			}
		}
		
		$info = model('ErpGoodsSpecificationsAttribute') -> find($id);
		
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑属性')
            ->addFormItems([
				['text', 'attribute_title', '规格属性'],
            ])
			->addText('sort', '排序')
			->setFormData($info)
            ->fetch();
	}
	
	public function delete($id = ''){
		if ($id === '') $this->error('缺少参数');
		$info = model('ErpGoodsSpecificationsAttribute') -> find($id);
		$goods_id     = $info['goods_id'];
		$attribute_id = $info['attribute_id'];

		$map1 = [
			['goods_id', '=', $goods_id],
			['specifications1_attribute_id', '=', $attribute_id],
		];
		$map2 = [
			['goods_id', '=', $goods_id],
			['specifications2_attribute_id', '=', $attribute_id],
		];
		$sku_info = model('ErpGoodsSku') -> whereOr([$map1, $map2]) ->  column('id');
		$sku_arr = [];
		$available_num = 0;
		foreach($sku_info as $sku_id){
			$map = [];
			$map[] = ['goods_id', '=', $goods_id];
			$map[] = ['sku_id', '=', $sku_id];
			$map[] = ['available_num', '>', 0];
			$goods_stock = model('ErpGoodsWarehouseStockNum') -> field('sum(available_num) as available_num') -> where($map) -> find();//库存 / 价格信息
			$available_num += $goods_stock['available_num'];
		}
		if($available_num < 1){
			$rel1 = model('ErpGoodsSku') -> destroy($sku_info);
			$rel2 = model('ErpGoodsSpecificationsAttribute') -> destroy($id);
			if ($rel1 && $rel2) {
				$this->success('删除成功');
			} else {
				$this->error('删除失败');
			}
		}else{
			$this->error('该规格下产品已在售卖中，无法删除');
		}
	}
}

